using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 死亡状态
/// </summary>
public class DeadState : IFsmState
{
    private Coroutine m_DestroyCoroutine;

    public void Enter(Entity entity, params object[] args)
    {
        Logger.Log($"【DeadState】 Enter ===>>> {entity.name}");
        
        // 检查是否是植物且没有死亡动画
        bool hasDeathAnimation = true;
        if (entity is Plant plant && plant.EntityData is PlantData plantData)
        {
            hasDeathAnimation = plantData.HasDeathAnimation;
            Logger.Log("DeadState", $"{entity.name} HasDeathAnimation: {hasDeathAnimation}");
        }
        
        // 如果没有死亡动画，直接销毁
        if (!hasDeathAnimation)
        {
            Logger.Log("DeadState", $"{entity.name} 没有死亡动画，直接销毁");
            if (Application.isPlaying)
            {
                GameObject.Destroy(entity.gameObject);
            }
            else
            {
                GameObject.DestroyImmediate(entity.gameObject);
            }
            return;
        }
        
        // 有死亡动画，等待动画播放完成
        if (entity.Animator != null)
        {
            entity.Animator.SetTrigger("die");
            
            // 启动协程等待动画播放完成后再销毁
            if (Application.isPlaying && entity != null)
            {
                m_DestroyCoroutine = entity.StartCoroutine(WaitForAnimationAndDestroy(entity));
            }
            else
            {
                // 编辑器中直接销毁
                GameObject.DestroyImmediate(entity.gameObject);
            }
        }
        else
        {
            // 没有Animator，直接销毁
            if (Application.isPlaying)
            {
                GameObject.Destroy(entity.gameObject);
            }
            else
            {
                GameObject.DestroyImmediate(entity.gameObject);
            }
        }
    }

    /// <summary>
    /// 等待动画播放完成后销毁对象
    /// </summary>
    private IEnumerator WaitForAnimationAndDestroy(Entity entity)
    {
        if (entity == null || entity.Animator == null)
        {
            yield break;
        }

        // 等待几帧，确保动画状态已经切换并开始播放
        yield return null;
        yield return null;

        // 获取当前播放的动画信息
        AnimatorStateInfo stateInfo = entity.Animator.GetCurrentAnimatorStateInfo(0);
        
        // 获取动画长度
        float animationLength = stateInfo.length;
        
        // 如果动画长度无效，使用默认值
        if (animationLength <= 0)
        {
            animationLength = 1f; // 默认1秒
            Logger.LogWarning("DeadState", $"{entity.name} 无法获取动画长度，使用默认值1秒");
        }

        // 保存状态hash用于比较
        int stateHash = stateInfo.fullPathHash;
        
        // 记录动画开始时的normalizedTime
        float startNormalizedTime = stateInfo.normalizedTime;
        
        Logger.Log("DeadState", $"{entity.name} 开始等待死亡动画，动画长度: {animationLength}秒，当前normalizedTime: {startNormalizedTime}, stateHash: {stateHash}");

        // 如果normalizedTime已经是1或更大，说明可能获取到的是之前的动画状态
        // 需要等待动画真正切换到死亡动画并开始播放
        if (startNormalizedTime >= 1f)
        {
            Logger.LogWarning("DeadState", $"{entity.name} 检测到normalizedTime已经是{startNormalizedTime}，等待死亡动画真正开始播放");
            
            // 等待动画状态切换到死亡动画，或者等待normalizedTime重置
            float waitForStartTime = 0f;
            float maxWaitForStart = 1f; // 最多等待1秒
            
            while (waitForStartTime < maxWaitForStart && entity != null && entity.Animator != null)
            {
                AnimatorStateInfo currentState = entity.Animator.GetCurrentAnimatorStateInfo(0);
                
                // 如果状态hash相同且normalizedTime小于1，说明动画开始播放了
                if (currentState.fullPathHash == stateHash && currentState.normalizedTime < 1f)
                {
                    startNormalizedTime = currentState.normalizedTime;
                    Logger.Log("DeadState", $"{entity.name} 死亡动画开始播放，normalizedTime: {startNormalizedTime}");
                    break;
                }
                
                // 如果状态hash不同，说明已经切换到新的动画状态
                if (currentState.fullPathHash != stateHash)
                {
                    // 更新状态信息
                    stateInfo = currentState;
                    stateHash = currentState.fullPathHash;
                    startNormalizedTime = currentState.normalizedTime;
                    animationLength = currentState.length > 0 ? currentState.length : 1f;
                    Logger.Log("DeadState", $"{entity.name} 动画状态已切换，新的stateHash: {stateHash}, normalizedTime: {startNormalizedTime}");
                    break;
                }
                
                waitForStartTime += Time.deltaTime;
                yield return null;
            }
        }

        // 等待动画播放完成
        // normalizedTime 从0到1表示动画播放进度
        float maxWaitTime = animationLength * 2f; // 最大等待时间（动画长度的2倍，防止无限等待）
        float elapsedTime = 0f;
        
        while (elapsedTime < maxWaitTime && entity != null && entity.Animator != null)
        {
            // 获取当前动画状态
            AnimatorStateInfo currentState = entity.Animator.GetCurrentAnimatorStateInfo(0);
            
            // 检查是否仍在同一个动画状态
            if (currentState.fullPathHash != stateHash)
            {
                // 动画状态已切换，可能动画已经结束或被打断
                Logger.LogWarning("DeadState", $"{entity.name} 动画状态已切换，可能动画已结束");
                break;
            }
            
            // 检查动画是否已经播放完成
            // normalizedTime >= 1 表示动画播放完成
            // 但是要确保normalizedTime确实从开始值增长到了1（防止一开始就是1的情况）
            if (currentState.normalizedTime >= 1f)
            {
                // 确保normalizedTime确实增长了（防止一开始就是1的情况）
                // 如果startNormalizedTime很小（<0.1），说明动画是从头开始播放的
                // 如果startNormalizedTime >= 1，但currentState.normalizedTime也>=1，说明动画可能已经播放完成
                if (startNormalizedTime < 0.1f || currentState.normalizedTime > startNormalizedTime)
                {
                    Logger.Log("DeadState", $"{entity.name} 动画播放完成，normalizedTime: {currentState.normalizedTime} (从 {startNormalizedTime} 增长)");
                    break; // 动画已播放完成
                }
                else
                {
                    // normalizedTime一开始就是1，继续等待
                    Logger.LogWarning("DeadState", $"{entity.name} normalizedTime一开始就是1，继续等待动画真正开始，当前: {currentState.normalizedTime}");
                }
            }

            elapsedTime += Time.deltaTime;
            yield return null;
        }

        //等待1秒后销毁
        //yield return new WaitForSeconds(1f);

        // 动画播放完成，销毁对象
        if (entity != null && entity.gameObject != null)
        {
            Logger.Log("DeadState", $"{entity.name} 死亡动画播放完成，销毁对象，等待时间: {elapsedTime}秒");
            GameObject.Destroy(entity.gameObject);
        }

        m_DestroyCoroutine = null;
    }

    public void Exit(Entity entity, params object[] args)
    {
        // 如果协程还在运行，停止它
        if (m_DestroyCoroutine != null && entity != null)
        {
            entity.StopCoroutine(m_DestroyCoroutine);
            m_DestroyCoroutine = null;
        }
    }

    public void Process(Entity entity, params object[] args)
    {
        // 死亡状态不需要处理逻辑
    }
}
